import os
import glob
# import subprocess
import sys

import cv2
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog, QGraphicsScene, QGraphicsView, QMessageBox
from PyQt5.QtGui import QImage, QPixmap
from MainWindow import Ui_MainWindow


class MainWindow(QMainWindow):

    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # 初始化QGraphicsView和QGraphicsScene
        self.graphicsView = self.findChild(QGraphicsView, 'graphicsView')
        self.scene = QGraphicsScene(self)
        self.graphicsView.setScene(self.scene)

        self.ui.importrefImage.clicked.connect(self.onimportrefImageClicked)
        self.ui.importImg.clicked.connect(self.onImportImageClicked)
        self.ui.importVideo.clicked.connect(self.onImportVideoClicked)
        self.ui.importButton.clicked.connect(self.onimportButtonClicked)
        self.ui.startTest.clicked.connect(self.onstartTestButtonClicked)

        self.board = None
        self.imgRef_path = None
        self.img_test = None
        self.scale_low = None
        self.scale_high = None
        self.span = None
        self.minRadius = None
        self.frame_interval = None

        self.image_count = None
    def onselectBoard(self):
        if self.radioButton_1.isChecked():
            self.board = 1
        elif self.radioButton_2.isChecked():
            self.board = 2
        elif self.radioButton_3.isChecked():
            self.board = 3
    def onimportrefImageClicked(self):
        # 打开文件对话框选择图片
        options = QFileDialog.Options()
        self.imgRef_path, _ = QFileDialog.getOpenFileName(self, "Select Image", "",
                                                  "Images (*.png *.xpm *.jpg *.bmp);;All Files (*)", options=options)

        if self.imgRef_path:
            self.imgRef_path = self.imgRef_path
            # 加载图片
            pixmap = QPixmap(self.imgRef_path)

            # 获取QGraphicsView的大小
            viewWidth = self.graphicsView.width()
            viewHeight = self.graphicsView.height()

            # 缩放图片以适应QGraphicsView的大小
            scaledPixmap = pixmap.scaled(viewWidth, viewHeight, Qt.KeepAspectRatio, Qt.SmoothTransformation)

            # 清除之前的场景，如果有的话
            if self.scene:
                self.scene.clear()

            # 如果场景不存在，创建一个
            if not self.scene:
                self.scene = QGraphicsScene(self)
                self.graphicsView.setScene(self.scene)

            # 将缩放后的图片添加到场景中
            self.scene.addPixmap(scaledPixmap)

            # 确保图片完全可见
            self.graphicsView.fitInView(self.scene.sceneRect(), Qt.KeepAspectRatio)

    def onImportImageClicked(self):
        self.img_test = QFileDialog.getExistingDirectory(self, "Select Directory")

    def onImportVideoClicked(self):

        # 打开文件对话框选择视频
        options = QFileDialog.Options()
        self.img_test, _ = QFileDialog.getOpenFileName(self, "Select Video", "",
                                                    "Videos (*.mp4 *.avi *.mov);;All Files (*)",
                                                    options=options)

    def onimportButtonClicked(self):
        self.ui.textEdit.setText("请先选择检测对象")
        if self.ui.importImg.isChecked():
            if self.img_test:
                image_extensions = ('*.png', '*.jpg', '*.jpeg', '*.gif')
                image_files = []
                for ext in image_extensions:
                    image_files.extend(glob.glob(os.path.join(self.img_test, ext)))
            if self.img_test:
                self.image_count = [f for f in os.listdir(self.img_test) if
                               f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif'))]
                self.image_count = len(image_files)
                self.ui.textEdit.setText(f"成功导入图片，文件夹中共有 {self.image_count} 张图片。")
                # subprocess.run(['python', 'dial.py', self.board, self.imgRef_path, self.img_test, self.frame_interval,
                #                 self.scale_low, self.scale_high, self.span, self.minRadius])
            else:
                self.ui.textEdit.setText("请先选择图片文件夹。")
        elif self.ui.importVideo.isChecked():
            frame_interval = self.ui.spinBox.value()
            if self.img_test and frame_interval > 0:
                # 计算将要抓取的图片数量
                cap = cv2.VideoCapture(self.img_test)
                # subprocess.run(['python', 'process_video.py', self.img_test, self.frame_interval])
                if not cap.isOpened():
                    self.ui.textEdit.setText("无法打开视频文件。")
                    cap.release()
                    return
                total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
                num_captured_frames = total_frames // frame_interval
                if total_frames % frame_interval != 0:
                    num_captured_frames += 1

                # 更新文本框内容
                fps = cap.get(cv2.CAP_PROP_FPS)
                total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))

                num_captured_frames = total_frames // frame_interval
                if total_frames % frame_interval != 0:
                    num_captured_frames += 1

                self.ui.textEdit.setText(f"总帧数: {total_frames}\n"
                                         f"帧率 (FPS): {fps:.2f}\n"
                                         f"帧间隔: {frame_interval}\n"
                                         f"估计捕获的帧数: {num_captured_frames}")

                # 释放视频捕获对象
                cap.release()
            else:
                self.ui.textEdit.setText("请先选择视频并设置有效的帧间隔。")

    def onstartTestButtonClicked(self):
        self.scale_low = self.lineEdit_1.text()
        self.scale_high = self.lineEdit_2.text()
        self.span = self.lineEdit_3.text()
        self.minRadius = self.lineEdit_4.text()

        processing_time_estimate = self.image_count * 5  # 每张图片处理需要5秒
        message = f"需要处理 {self.image_count} 张图片，预计需要 {processing_time_estimate} 秒"

        self.ui.textEdit_res.setText(message)



if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainWindow = MainWindow()  # 实例化你新创建的类
    mainWindow.show()  # 显示窗口
    sys.exit(app.exec_())